package Beans;

import Entidades.Person;
import SessionBeans.PersonFacade;
import SessionBeans.util.JsfUtil;
import SessionBeans.util.PaginationHelper;
import java.io.Serializable;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.ejb.EJBAccessException;
import javax.ejb.EJBException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.faces.application.FacesMessage;

@ManagedBean(name = "personController")
@SessionScoped
public class PersonController implements Serializable {

    private String login;
    private String senha;
    private Person current; // para a CRUD dos usuarios... soh o adm pode mexer neles... a nao ser que o usuario seja criado
    private Person userCurrent = new Person(); // guarda o usuario que está logado no momento  
    private Boolean logado = false;
    private DataModel items = null;
    @EJB
    private SessionBeans.PersonFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;

    public PersonController() {
    }

    public Person getSelected() {
        if (current == null) {
            current = new Person();
            selectedItemIndex = -1;
        }
        return current;
    }

    public Person getUserCurrent() {
        return userCurrent;
    }

    public void setUserCurrent(Person userCurrent) {
        this.userCurrent = userCurrent;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getSenha() {
        return senha;
    }

    public void setSenha(String senha) {
        this.senha = senha;
    }

    public Person getCurrent() {
        return current;
    }

    public void setCurrent(Person current) {
        this.current = current;
    }

    public Boolean getLogado() {
        return logado;
    }

    public void setLogado(Boolean logado) {
        this.logado = logado;
    }

    private PersonFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {
                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String logar() throws Error, NullPointerException {
        userCurrent = new Person();
        System.out.println("Usuario: " + this.login);


        try {
            if (this.login == null || this.senha == null) {
                return "/errologar"; //não autenticou
            }
            System.out.println(">>>>>>>>>" + userCurrent.getLogin() + " == " + this.login);
            userCurrent = ejbFacade.find(this.login);
            System.out.println(">>>>>>>>>" + userCurrent.getLogin() + " == " + this.login);
            if (userCurrent.getSenha().equals(this.senha)) {
                //inseri na sessão o usuario autenticado
                FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("userCurrent", userCurrent);
                System.out.println("colocando usuario na Sessao" + FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userCurrent"));
                FacesMessage msg = new FacesMessage("Successful", "Welcome :" + userCurrent.getName());
                FacesContext.getCurrentInstance().addMessage(null, msg);

                System.out.println("Inseriu user corrent na sessão");
                System.out.println("usuario corrent ok ");
                System.out.println(userCurrent.getLogin());
                this.logado = true;
            } else {

                FacesMessage msg = new FacesMessage("ERROR", "Usuário não existe ");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return "/errorlogar";

            }

        } catch (EJBException ex) {

            FacesMessage msg = new FacesMessage("ERROR", "Usuário não existe ");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            System.out.println("Error:" + ex);
            return "/errologar"; //não autenticou

        }

        return "/home";
    }

    public Boolean ehAdmin() {

        try {
            if (((Person) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userCurrent")) == null) {
                return false;

            } else if (((Person) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userCurrent")).getIsAdmin()) {
                return true;

            } else {
                return false;
            }
        } catch (NullPointerException e) {
            System.out.println("Error: " + e);
            return false;

        }

    }

    public String logOut() {

        System.out.println("logout: usuario:" + userCurrent.toString());
        userCurrent = null;
        this.logado = false;
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("userCurrent", null);


        return "/login";
    }

    public String verificaPaginaAdm() throws NullPointerException {
        try {
            System.out.println("verifica pagina de ADM");
            System.out.println(">>>>" + userCurrent.getLogin());

            System.out.println("user da sessao" + ((Person) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userCurrent")));
            if (((Person) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userCurrent")) == null) {
                System.out.println(((Person) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userCurrent")));
                FacesMessage msg = new FacesMessage("Error", "Favor Efetuar LOGIN ");
                FacesContext.getCurrentInstance().addMessage(null, msg);
                return "/login";
            } else if (((Person) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userCurrent")) != null) {
                if (((Person) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userCurrent")).getIsAdmin()) {
                    FacesMessage msg = new FacesMessage("Successful", "Welcome :" + userCurrent.getName());
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                    return "/indexAdmin";

                } else {
                    FacesMessage msg = new FacesMessage("Error", "Acesso Restrito ");
                    FacesContext.getCurrentInstance().addMessage(null, msg);
                    return "/home";
                }

            }
        } catch (NullPointerException e) {

            FacesMessage msg = new FacesMessage("Error", "Acesso Restrito " + e);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            return "/home";
        }

        return "/home";
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (Person) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Person();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            //current.setSenha();
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PersonCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (Person) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

     public String prepareEditSession() {
        current = (Person) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userCurrent");
        return "Edit";
    }
    
    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PersonUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (Person) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PersonDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = Person.class)
    public static class PersonControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            PersonController controller = (PersonController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "personController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Person) {
                Person o = (Person) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Person.class.getName());
            }
        }
    }
}
